#!/bin/bash
set -ex

declare -x HOST_PASSWORD
declare -x TARGET_DIR
declare -x HARBOR_DATA
declare -x HARBOR_LOG
declare -x HARBOR_DIR

cur_dir=$(dirname "$(readlink -f "$0")")
TARGET_DIR="$cur_dir"/app
CONFIG_FILE="$cur_dir"/config.json
HARBOR_DIR="$TARGET_DIR/harbor"

yq() {
    "$cur_dir"/app/yq_linux_amd64 "$@"
}

preset() {
    if [ ! -d "$TARGET_DIR" ]; then
        mkdir -p "$TARGET_DIR"
    fi
    found_files=$(find "$TARGET_DIR" -type f -name "yq*" )
    if [ -z "$found_files" ]; then
        echo "安装 yq ..."
        wget -c https://github.com/mikefarah/yq/releases/download/v4.2.0/yq_linux_amd64.tar.gz -O - |\
            tar xz && mv yq_linux_amd64 "$TARGET_DIR"
    fi
    HOST_PASSWORD=$(yq eval '.host_passowd' "$CONFIG_FILE")
    HARBOR_DATA=$(yq eval '.harbor_data' "$CONFIG_FILE")
    HARBOR_LOG=$(yq eval '.harbor_log' "$CONFIG_FILE")
}

download_and_verify() {
    local filename="$1"
    local url="$2"
    local md5Url="$3"
    local targetDir="$4"

    wget -c -O "${targetDir}/${filename}" "$url"

    # 有的网络资源没有提供 md5
    if [[ "$md5Url" != "false" ]]; then
        wget -c -O "${targetDir}/${filename}.md5" "$md5Url"
        read -r md5Value < "${targetDir}/${filename}.md5"
        if echo "${md5Value} ${targetDir}/${filename}" | md5sum -c --quiet; then
            echo "文件${filename}已成功下载且MD5校验通过。"
        else
            echo "警告：文件${filename}的MD5校验失败。"
        fi
    fi
}
